/**
 * 微信视频号店铺体验分数据port
 * 数据处理
 */

import moment from "moment"

import type { PlasmoMessaging } from "@plasmohq/messaging"

// 数据记录
let scoreData = {}
// 校验总键数
let totalKeys = 0
// 键名列表
let keysList = []

// 初始化数据
const initData = () => {
  scoreData = {}
}

// 更新scoreData
const updateScoreData = (data: any) => {
  scoreData = {
    ...scoreData,
    ...data
  }
}

/*** 拦截数据处理器 ***/
// 数据解释器
const pareserData = (data: any) => {
  // 数据处理
  // 同一个请求url根据params返回不同的结果，所以直接判断data是否含有对应的字段
  // 查询字段map
  const queryFieldMap = [
    // L1
    { field: "endDate", label: "日期" },
    { field: "dsrScore", subField: "curValue", label: "店铺体验分" },
    { field: "productScore", subField: "curValue", label: "商品体验" },
    { field: "deliverScore", subField: "curValue", label: "物流体验" },
    { field: "serviceScore", subField: "curValue", label: "服务体验" },
    // 商品 L2
    {
      field: "productQualityRatio_30d",
      subField: "curValue",
      label: "品质退款率"
    },
    {
      field: "productQualityRatio_30d",
      subField: "rankRatio",
      label: "品质退款率|超越同行"
    },
    {
      field: "proValidGoodEvalRatio",
      subField: "curValue",
      label: "商品好评率"
    },
    {
      field: "proValidGoodEvalRatio",
      subField: "rankRatio",
      label: "商品好评率|超越同行"
    },
    // 物流 L2
    {
      field: "collectInTimeRatio_30d",
      subField: "curValue",
      label: "及时揽收率"
    },
    {
      field: "collectInTimeRatio_30d",
      subField: "rankRatio",
      label: "及时揽收率|超越同行"
    },
    // 服务 L2
    {
      field: "serviceReplyLength_30d",
      subField: "curValue",
      label: "平均回复时长"
    },
    {
      field: "serviceReplyLength_30d",
      subField: "rankRatio",
      label: "平均回复时长|超越同行"
    },
    {
      field: "serviceNoreplyRatio_30d",
      subField: "curValue",
      label: "不回复率"
    },
    {
      field: "serviceNoreplyRatio_30d",
      subField: "rankRatio",
      label: "不回复率|超越同行"
    },
    {
      field: "aftersaleFirstOperationTime_30d",
      subField: "curValue",
      label: "售后首次操作时长"
    },
    {
      field: "aftersaleFirstOperationTime_30d",
      subField: "rankRatio",
      label: "售后首次操作时长|超越同行"
    },
    {
      field: "onlyRefundDealSec_30d",
      subField: "curValue",
      label: "退款自主完结时长"
    },
    {
      field: "onlyRefundDealSec_30d",
      subField: "rankRatio",
      label: "退款自主完结时长|超越同行"
    },
    {
      field: "returnRefundDealSec_30d",
      subField: "curValue",
      label: "退货退款自主完结时长"
    },
    {
      field: "returnRefundDealSec_30d",
      subField: "rankRatio",
      label: "退货退款自主完结时长|超越同行"
    },
    {
      field: "serviceComplaintRatio_30d",
      subField: "curValue",
      label: "商责纠纷率"
    },
    {
      field: "serviceComplaintRatio_30d",
      subField: "rankRatio",
      label: "商责纠纷率|超越同行"
    },
    // 商品 L3
    {
      field: "proValidGoodEvalCnt_30d",
      subField: "curValue",
      label: "近30天好评数"
    },
    {
      field: "proValidEvalCnt_30d",
      subField: "curValue",
      label: "近30天评价数"
    },
    {
      field: "shipProductQualityRefundOrdCnt_30d",
      subField: "curValue",
      label: "近30天品质退款订单量"
    },
    {
      field: "shopOrdCnt_30d",
      subField: "curValue",
      label: "近30天已发货订单量"
    },
    // 物流 L3
    {
      field: "collectInTimeOrdCnt_30d",
      subField: "curValue",
      label: "近30天及时揽收的订单量"
    },
    {
      field: "collectDoneOrdCnt_30d",
      subField: "curValue",
      label: "近30天应揽收订单量"
    },
    // 服务 L3
    {
      field: "replySecondLength_30d",
      subField: "curValue",
      label: "近30天人工回复时长之和"
    },
    {
      field: "replyRoundCnt_30d",
      subField: "curValue",
      label: "近30日人工咨询轮次总数"
    },
    {
      field: "noreplyRoundCnt_30d",
      subField: "curValue",
      label: "近30天人工未回复轮次数"
    },
    {
      field: "roundCnt_30d",
      subField: "curValue",
      label: "近30天人工咨询轮次总数"
    },
    {
      field: "afterSaleFirstOperationSecond_30d",
      subField: "curValue",
      label: "近30天售后商家首次操作时长之和"
    },
    {
      field: "afterSaleFirstOperationOrdCnt_30d",
      subField: "curValue",
      label: "近30天售后单量"
    },
    {
      field: "refundShopDealSecond_30d",
      subField: "curValue",
      label: "近30天退款售后单等待商家操作总时长"
    },
    {
      field: "afterSaleOnlyRefundOrdCnt_30d",
      subField: "curValue",
      label: "近30天退款售后单量"
    },
    {
      field: "refundReturnShopDealSecond_30d",
      subField: "curValue",
      label: "近30天退货退款售后单等待商家操作总时长"
    },
    {
      field: "afterSaleOrdCnt_30d",
      subField: "curValue",
      label: "近30天退货退款售后单量"
    },
    {
      field: "complaintOrdCnt_30d",
      subField: "curValue",
      label: "近30天商责纠纷订单量"
    },
    { field: "ordCnt_30d", subField: "curValue", label: "近30天有效支付订单量" }
  ]
  const temp = {}
  // 循环查询字段map
  for (const item of queryFieldMap) {
    if (data[item.field] !== undefined) {
      if (item.subField) {
        temp[item.label] =
          data[item.field][item.subField] !== undefined
            ? data[item.field][item.subField]
            : 0
      } else {
        temp[item.label] = data[item.field]
      }
      // 格式化日期
      if (item.label === "日期") {
        temp[item.label] = moment(temp[item.label]).format("YYYY-MM-DD") || ""
      }
    }
  }
  // 写入scoreData
  updateScoreData(temp)
}

// port handler
const handler: PlasmoMessaging.PortHandler = async (req, res) => {
  const { url, data, params, action } = req.body
  switch (action) {
    case "clear":
      // 清空数据
      initData()
      break
    case "setKeys":
      // 设置数据键值总量
      totalKeys = data?.count || 0
      keysList = data?.fields || []
      break
    case "inspect":
      // 轮询处理拦截数据
      pareserData(data)
      break
    default:
      break
  }

  // console.log("scoreData", scoreData)

  res.send({
    data: scoreData,
    keysList,
    rate: ((Object.keys(scoreData).length / totalKeys) * 100).toFixed(0)
  })
}

export default handler
